import Drawer from "@src/components/Drawer";
import React, {useEffect} from "react";
import "./index.scss";
import * as Yup from "yup";
import {useFormik} from "formik";
import FormInputIcon from "@src/pages/logIn/_components/formInputIconProps";
import UserIcon from "@src/assets/user.svg?react";
import HeadList from "@src/components/headList";
import toast from 'react-hot-toast';
import {usersUpdate} from "@src/services/userinfo.ts";
import {useRequest} from "ahooks";
import {getUserInfo} from "@src/utils/userInfo"

interface FromType {
    name: string;
    gender: 'male' | 'female' | null;
    birthdate: string;
    avatar: string;
}

export interface SetUserinfoProps extends React.HTMLProps<HTMLDivElement> {
    isOpen: boolean; // 当前的显示状态
    setIsOpen: React.Dispatch<React.SetStateAction<boolean>>; // 用于改变状态的函数
}

export default function SetUserinfo({isOpen, setIsOpen}: SetUserinfoProps) {
    const usersUpdateApi = useRequest(usersUpdate, {manual: true});
    const {user, token} = getUserInfo()
    const initialValues: FromType = {
        name: user.name,
        gender: user.gender,
        birthdate: user.birthdate,
        avatar: user.avatar
    };

    const formik = useFormik<FromType>({
        initialValues,
        validationSchema: Yup.object({
            name: Yup.string().required("昵称是必须的哦~").matches(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, '不能包含特殊字符'),
        }),
        onSubmit: (values) => {
            if (values.birthdate == "" || values.birthdate == null) {
                values.birthdate = null as unknown as string
            } else {
                values.birthdate = values.birthdate.toString().split("T")[0]
            }
            if (token) {
                usersUpdateApi.runAsync(values.name, values.gender, values.birthdate, values.avatar, token).then((result) => {
                    toast.success("成功保存(●'◡'●)")
                    if (result.data.user.birthdate !== null) {
                        result.data.user.birthdate = result.data.user.birthdate.split("T")[0]
                    }
                    localStorage.setItem("UserData", JSON.stringify(result.data));
                    setIsOpen(false)
                })
            }
        },
    });

    useEffect(() => {
        if (!isOpen) {
            formik.setErrors({})
            formik.values.name = user.name;
            formik.values.gender = user.gender;
            formik.values.birthdate = user.birthdate;
            formik.values.avatar = user.avatar;
        }
    }, [isOpen])

    return (
        <Drawer position="bottom" height={"70%"} isOpen={isOpen} setIsOpen={setIsOpen}>
            <form className="SetUserinfo" onSubmit={formik.handleSubmit}>
                <ul>
                    <li className="name">
                        <p>姓名</p>
                        <FormInputIcon
                            Icon={<UserIcon/>}
                            name="name"
                            value={formik.values.name}
                            placeholder="请输入昵称"
                            formik={formik}
                        />
                    </li>
                    <li className="birthdate">
                        <p>生日</p>
                        <div className="inputIcon">
                            <input
                                type="date"
                                name="birthdate"
                                value={formik.values?.birthdate}
                                onChange={formik.handleChange}
                            />
                        </div>
                    </li>

                    <li className="gender">
                        <p>性别</p>
                        <div>
                            <label>
                                <input
                                    type="radio"
                                    name="gender"
                                    value="female"
                                    checked={formik.values.gender === "female"}
                                    onChange={formik.handleChange}
                                />
                                男
                            </label>
                            <label>
                                <input
                                    type="radio"
                                    name="gender"
                                    value="male"
                                    checked={formik.values.gender === "male"}
                                    onChange={formik.handleChange}
                                />
                                女
                            </label>
                        </div>
                    </li>

                    <li className="avatar">
                        <p>头像</p>
                        <HeadList addHeadUrl={user.avatar?[user.avatar]:[]}
                                  onChange={(url) => formik.values.avatar = url}></HeadList>
                    </li>
                </ul>
                <div className="bottom">
                    <button type="button" className="z-button" onClick={() => setIsOpen(false)}>
                        取消
                    </button>
                    <button type="submit" className="z-button">保存</button>
                </div>
            </form>
        </Drawer>
    );
}